#include "HelloTriangles.h"
#include "Shader.h"
#include "Vertex.h"
#include "Timer.h"
#include "Texture.h"

Shader* shader = NULL;
GLuint vboId;
Texture* texture;
HelloTriangles::HelloTriangles(void)
{
	//Constructor
}

void HelloTriangles::Init()
{
	int * leakMemory = new int;
	texture = new Texture();
	texture->Init("../Resources/Woman1.tga");
	textureId = texture->GetTextureId();
	Vertex verticesData[4];

	verticesData[0].position =  Vector3(0.5f, 0.5f, 0.0f);
	verticesData[1].position = Vector3(-0.5f, -0.5f, 0.0f); 
	verticesData[2].position = Vector3(0.5f, -0.5f, 0.0f);
	verticesData[3].position =  Vector3(-0.5f, 0.5f, 0.0f);
	verticesData[0].uv = Vector2(0.0f,0.0f);
	verticesData[1].uv = Vector2(1.0f,1.0f);
	verticesData[2].uv = Vector2(0.0f,1.0f);
	verticesData[2].uv = Vector2(1.0f,0.0f);
	
	unsigned int* indiData;
	indiData  =new unsigned int[6];
	indiData[0] = 0;
	indiData[1] = 1;
	indiData[2] = 2;
	indiData[3] = 0;
	indiData[4] = 1;
	indiData[5] = 3;
	glGenBuffers(1, &iboId);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboId);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int)*6, indiData,
	GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	//buffer object
	glGenBuffers(1, &vboId);
	glBindBuffer(GL_ARRAY_BUFFER, vboId);
	glBufferData(GL_TRIANGLES, sizeof(verticesData), verticesData, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	
	shader = new Shader();
	shader->Init("../Resources/Shaders/Basic.vs", "../Resources/Shaders/Basic.fs");
}
void HelloTriangles::Update()
{
	//LOGI("\nFrame time: %f (s)", Timer::FrameTime() );
}

void HelloTriangles::Render()
{
	glEnable(GL_DEPTH_TEST);
	glUseProgram(shader->program);

	glBindBuffer(GL_ARRAY_BUFFER, vboId);
	
	if(shader->a_positionLoc != -1)
	{
		glEnableVertexAttribArray(shader->a_positionLoc);
		glVertexAttribPointer(shader->a_positionLoc, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void *) offsetof(Vertex, position));
	}
	if(shader->a_colorLoc != -1){
		glEnableVertexAttribArray(shader->a_colorLoc);
		glVertexAttribPointer(shader->a_colorLoc,2,GL_FLOAT,GL_FALSE, sizeof(Vertex), (void*) offsetof(Vertex,uv));
	}
	if(shader->u_textureLoc  != -1){
		glUniform1i(shader->u_textureLoc,0);
	}
	glActiveTexture(textureId);
	glBindTexture(GL_TEXTURE_2D,textureId);


	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboId);
	//glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

	glBindBuffer(GL_ARRAY_BUFFER, 0);	
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
	glBindBuffer(GL_TEXTURE_2D,0);
	glDisable(GL_DEPTH_TEST);
}
void HelloTriangles::Destroy()
{
	SAFE_DEL(shader);

	if (vboId != 0)
	{
		glDeleteBuffers(1, &vboId);
		vboId = 0;
	}
}
HelloTriangles::~HelloTriangles(void)
{
	Destroy();
}
